/*
 *  Copyright (C) void Team 2010 Pedro Batista
 *
 *  http://code.google.com/p/capacitec
 *
 *  This file is part of capacitec.
 *
 *  capacitec is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  capacitec is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with capacitec.  If not, see <http://www.gnu.org/licenses/>.
 */
package infra;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
import br.com.caelum.vraptor.ioc.SessionScoped;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Classe responsável por carregar o sessões do hibernate para manipulação
 * de dados do banco.
 * @author pedro
 */
@Component @SessionScoped
public class CriadorDeSession implements ComponentFactory<Session>{

	/**
	 * Instancias do criador de sessões do hibernate já configurado.
	 */
	SessionFactory sessionFactory;
	/**
	 * Sessão do hibernate gerada pelo sessionFactory.
	 */
	Session session;

	/**
	 * Cria uma instancia do CriadorDeSession.
	 * @param sessionFactory
	 */
	public CriadorDeSession(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Deve ser executado assim que a classe for instanciada para poder
	 * user a sessão.
	 */
	@PostConstruct
	public void abre(){
		this.session = sessionFactory.openSession();
	}

	/**
	 * Acessa a sessão do hibernate para permitir a manipulação de dados
	 * no banco.
	 * @return Sessão aberta.
	 * @throws HibernateException
	 */
	@Override
	public Session getInstance() throws HibernateException {
		//File config = new File("." + File.separator + "src" + File.separator + "hibernate.cfg.xml");
		return this.session;
	}

	/**
	 * Deve ser usado quando não se deseja mais manipular dados do banco com
	 * a sessão.
	 */
	@PreDestroy
	public void fecha(){
		this.session.close();
	}
}
